package com.szyjjk.util;

import com.alibaba.fastjson.JSONObject;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSelect;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;


import javax.imageio.ImageIO;
import javax.net.ssl.SSLContext;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author yangyue
 * @Description //TODO http 工具类
 * @Date 9:59 2020/3/24
 * @Param
 * @return
 **/
public class HttpTool {


    /**
     * @return java.lang.String
     * @Author yangyue
     * @Description //TODO Get请求
     * @Date 14:41 2020/3/24
     * @Param [urls, head]
     **/
    public static String doGetOnther(String urls, Map<String, String> head) throws Exception {
        SSLContext sslContext = new SSLContextBuilder()
                .loadTrustMaterial(null, (certificate, authType) -> true).build();
        CloseableHttpClient client = HttpClients.custom()
                .setSslcontext(sslContext)
                .setSSLHostnameVerifier(new NoopHostnameVerifier())
                .build();
        HttpGet httpGet = new HttpGet(urls);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(20000)
                .setSocketTimeout(20000)
                .setConnectTimeout(50000).build();
        httpGet.setConfig(requestConfig);
        if (head != null) {
            for (Object map : head.entrySet()) {
                httpGet.setHeader((String) ((Map.Entry) map).getKey(), (String) ((Map.Entry) map).getValue());
            }
        }
        httpGet.setHeader("accept", "*/*");
        httpGet.setHeader("connection", "Keep-Alive");
        httpGet.setHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        HttpResponse response = client.execute(httpGet);
        String resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        return resultString;
    }


    /**
     * @return java.lang.String
     * @Author yangyue
     * @Description //TODO POST 请求  JSON 当参数
     * @Date 15:06 2020/3/24
     * @Param [json, url]
     **/
    public static String post(JSONObject json, String url) {
        String result = "";
        HttpPost post = new HttpPost(url);
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();

            post.setHeader("Content-Type", "application/json;charset=utf-8");
            post.addHeader("Authorization", "Basic YWRtaW46");
            StringEntity postingString = new StringEntity(json.toString(), "utf-8");
            post.setEntity(postingString);
            HttpResponse response = httpClient.execute(post);

            InputStream in = response.getEntity().getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null) {
                strber.append(line + '\n');
            }
            br.close();
            in.close();
            result = strber.toString();
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                result = "服务器异常";
            }
        } catch (Exception e) {
            System.out.println("请求异常");
            throw new RuntimeException(e);
        } finally {
            post.abort();
        }
        return result;
    }


    public static String getRandomChar(int length) {            //生成随机字符串
        char[] chr = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
        Random random = new Random();
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < length; i++) {
            buffer.append(chr[random.nextInt(36)]);
        }
        return buffer.toString();
    }

    /**
     * @return boolean
     * @Author yangyue
     * @Description //TODO 下载图片
     * @Date 14:36 2020/4/2
     * @Param [imageUrl, formatName, localFile]
     **/
    public static boolean downloadImage(String imageUrl, String formatName, File localFile) {
        if(!localFile.getParentFile().exists()){
            localFile.mkdirs();
        }
        boolean isSuccess = false;
        URL url = null;
        try {
            url = new URL(imageUrl);
            isSuccess = ImageIO.write(ImageIO.read(url), formatName, localFile);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return isSuccess;
    }


    public static String waterHTML(String type) {
        String htmlString = "";
        int i = 0;
        try {
            String waterUrl = "https://cd.epic.epd.gov.hk/EPICRIVER/marinerecent/";
            // 模拟一个浏览器
            WebClient webClient = new WebClient(BrowserVersion.CHROME);
//        // 设置webClient的相关参数
//        webClient.setCssErrorHandler(new SilentCssErrorHandler());
//        //设置ajax
//        webClient.setAjaxController(new NicelyResynchronizingAjaxController());
//        //设置支持js
//        webClient.getOptions().setJavaScriptEnabled(true);
//        //CSS渲染禁止
//        webClient.getOptions().setCssEnabled(false);
            //超时时间
            webClient.getOptions().setTimeout(50000);
            //允许重定向
            webClient.getOptions().setRedirectEnabled(true);

            //设置SSL
            webClient.getOptions().setUseInsecureSSL(true);
            // 模拟浏览器打开一个目标网址
            HtmlPage page = webClient.getPage(waterUrl);
            /**等待js加载完全，CSDN这点 特别坑，js加载时间超长！！！！！！！ 后人切记不要用CSDN模拟登陆！！！！！！！**/
            webClient.waitForBackgroundJavaScript(10000 * 3);
            // 根据form的名字获取页面表单，也可以通过索引来获取：page.getForms().get(0)
            HtmlForm form = (HtmlForm) page.getElementById("form");
            HtmlSelect selectFrom = form.getSelectByName("form:wzterControlZone");
            selectFrom.setDefaultValue(type);

            HtmlElement a = (HtmlElement) page.getElementById("form:select");
            HtmlPage retPage = a.click();
            // 等待JS驱动dom完成获得还原后的网页
            webClient.waitForBackgroundJavaScript(1000);
            //输出跳转网页的地址
//        //输出跳转网页的内容
            htmlString = retPage.asXml();
            webClient.close();
        } catch (Exception e) {
            i++;
            if (i < 10) {
                waterHTML(type);
            }
        }
        return htmlString;
    }


    public static String StringTrim(String value) {
        return value.replace("</td>", "").replace("\n", "").replace(" ", "").replace("\r", "");
    }


    //日期格式化 时分秒归零 //
    public static Date simpToData(Date newData) {
        try {
            return shotSimpDate.parse(longSimpDate.format(newData));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static SimpleDateFormat longSimpDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    public static SimpleDateFormat BinarySimpDate = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss");
    public static SimpleDateFormat shotSimpDate = new SimpleDateFormat("yyyy-MM-dd");
    public static SimpleDateFormat monthSimpDate = new SimpleDateFormat("yyyy-MM");

    public static SimpleDateFormat HardimpDate = new SimpleDateFormat("yyyy/MM/dd hh:mm");
    public static SimpleDateFormat FilesDate = new SimpleDateFormat("yyyyMMdd");


//    public  static String ImageToBase64(String imgPath) {
//        byte[] data = null;
//        // 读取图片字节数组
//        try {
//            InputStream in = new FileInputStream(imgPath);
//            data = new byte[in.available()];
//            in.read(data);
//            in.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        // 对字节数组Base64编码
//        BASE64Encoder encoder = new BASE64Encoder();
//        // 返回Base64编码过的字节数组字符串
//       return encoder.encode(Objects.requireNonNull(data));
//    }


    /**
     * @return long
     * @Author yangyue
     * @Description //TODO 频率转毫秒
     * @Date 15:00 2020/4/22
     * @Param [type]
     **/
    public static long typeToLong(String type) {
        long timecha = 0;
        switch (type) {
            case "一小时一次":
                timecha = 3600000;
                break;
            case "一天一次":
                timecha = 86400000;
                break;
            case "一周一次":
                timecha = 604800000;
                break;
            case "一月一次":
                timecha = 2592000000L;
                break;
            case "一年一次":
                timecha = 31536000000L;
                break;
        }
        return timecha;
    }

    /**
     * 判断是不是昨天、明天
     *
     * @param day1
     * @return
     */
    public static boolean isYestoday(Date day1) {
        Calendar instance = Calendar.getInstance();
        instance.setTime(day1);
        int d1 = instance.get(Calendar.DAY_OF_YEAR);
        instance.setTime(new Date());
        int d2 = instance.get(Calendar.DAY_OF_YEAR);
        return d1 - d2 == 1 || d2 - d1 == 1;
    }

    /**
     * @return java.util.Date[]
     * @Author yangyue
     * @Description //TODO 输入时间返回当天0点和23:59：59
     * @Date 15:21 2020/5/19
     * @Param [newDate]
     **/
    public Date[] get0And12(Date newDate) {
        Date[] result = new Date[2];
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(newDate);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        result[0] = calendar.getTime();
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        result[1] = calendar.getTime();
        return result;
    }


}
